#coding=utf-8
#
require 'grape'
require File.join(Rails.root, "lib/api/api")

module API
    class API < Grape::API
    end

    class Users < Grape::API
      resource :users do
        put "/ext/:id" do
          authenticated_as_admin!

          ## 增加encrypted_password 和 password_salt字段
          attrs = attributes_for_keys [:encrypted_password, :password_salt, :email, :name, :password, :skype, :linkedin, :twitter, :website_url, :projects_limit, :username, :bio, :can_create_group, :admin]
          user = User.find(params[:id])
          not_found!('User') unless user

          admin = attrs.delete(:admin)
          user.admin = admin unless admin.nil?

          conflict!('Email has already been taken') if attrs[:email] &&
            User.where(email: attrs[:email]).
            where.not(id: user.id).count > 0

          conflict!('Username has already been taken') if attrs[:username] &&
            User.where(username: attrs[:username]).
            where.not(id: user.id).count > 0

          if user.update_attributes(attrs)
            present user, with: Entities::UserFull
          else
            render_validation_error!(user)
          end
        end
      end
    end

    class Projects < Grape::API
      resource :projects do
        helpers do
          def map_public_to_visibility_level(attrs)
            publik = attrs.delete(:public)
            publik = parse_boolean(publik)
            attrs[:visibility_level] = Gitlab::VisibilityLevel::PUBLIC if !attrs[:visibility_level].present? && publik == true
            attrs
          end

          def filter_projects(projects)
            # If the archived parameter is passed, limit results accordingly
            if params[:archived].present?
              projects = projects.where(archived: parse_boolean(params[:archived]))
            end

            if params[:search].present?
              projects = projects.search(params[:search])
            end

            if params[:ci_enabled_first].present?
              projects.includes(:gitlab_ci_service).
                reorder("services.active DESC, projects.#{project_order_by} #{project_sort}")
            else
              projects.reorder(project_order_by => project_sort)
            end
          end

          def project_order_by
            order_fields = %w(id name path created_at updated_at last_activity_at)

            if order_fields.include?(params['order_by'])
              params['order_by']
            else
              'created_at'
            end
          end

          def project_sort
            if params["sort"] == 'asc'
              :asc
            else
              :desc
            end
          end
        end


        post "/ext/user/:user_id" do
          authenticated_as_admin!
          user = User.find(params[:user_id])
          # 增加path字段
          attrs = attributes_for_keys [:name,
                                       :path,
                                       :description,
                                       :default_branch,
                                       :issues_enabled,
                                       :merge_requests_enabled,
                                       :wiki_enabled,
                                       :snippets_enabled,
                                       :public,
                                       :visibility_level,
                                       :import_url]
          attrs = map_public_to_visibility_level(attrs)
          @project = ::Projects::CreateService.new(user, attrs).execute
          if @project.saved?
            present @project, with: Entities::Project
          else
            render_validation_error!(@project)
          end
        end
      end
    end

end

